package com.supor.aiot.common.utils;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;

import com.alipay.xmedia.common.biz.utils.DeviceUtils;
import com.android.baseconfig.common.utils.Logc;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Consumer;

/**
 * @author: zook
 * @date: 2022/1/7
 */
public class ClassLoaderFixHelper {
    public final static ArrayList<String> fixAndroidQDeviceArr
            = new ArrayList<>(Arrays.asList(
            "OXF-AN10", "ANA-AN00", "NOH-AN01", "ELS-AN10", "ELE-AL00",
            "NOH-AN00", "LIO-AN00", "MI 9", "REDMI 8A", "V1962A", "V1986A",
            "PDPM00", "V1938CT", "VOG-AL10", "ELS-AN00"

    ));
    public final static ArrayList<String> fixAndroidPieDeviceArr
            = new ArrayList<>(Arrays.asList(
            "OXF-AN10", "ANA-AN00", "NOH-AN01", "ELS-AN10", "ELE-AL00",
            "NOH-AN00", "LIO-AN00", "MI 9", "REDMI 8A", "V1962A", "V1986A",
            "PDPM00", "V1938CT", "VOG-AL10", "ELS-AN00"
    ));

    public static boolean needFix() {
        Logc.d("ClassLoaderFixHelper", "Build.MODEL==" + Build.MODEL);
        return Build.VERSION.SDK_INT == Build.VERSION_CODES.Q && fixAndroidQDeviceArr.contains(Build.MODEL)
                || Build.VERSION.SDK_INT == Build.VERSION_CODES.P && fixAndroidPieDeviceArr.contains(Build.MODEL);
    }

    public static void intercept(Context context, Bundle bundle) {
        if (bundle != null && needFix()) {
            bundle.setClassLoader(context.getClassLoader());
            Logc.d("ClassLoaderFixHelper", "fixed");
        }
    }

    public static void interceptLifecycleClassloader(Context context, Bundle bundle) {
        if (bundle != null && context != null && needFix()) {
            bundle.setClassLoader(context.getClass().getClassLoader());
            Bundle keyBundle = bundle.getBundle("androidx.lifecycle.BundlableSavedStateRegistry.key");
            if (null != keyBundle) {
                ArrayList<String> list = new ArrayList<>(keyBundle.keySet());
                for (int i = 0; i < list.size(); i++) {
                    String key = list.get(i);
                    ((Bundle) keyBundle.get(key)).setClassLoader(context.getClass().getClassLoader());
                }
            }
        }
    }
}
